/**
 *====================================================
 * 文件名称: TallyingCastor.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年11月19日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.project.action.v1.dto;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.core.BusinessException;
import com.yuexunit.finance.bulkstock.entity.BulkstockInfoEntity;
import com.yuexunit.finance.bulkstock.entity.lexicon.MeasurementEnum;
import com.yuexunit.finance.bulkstock.service.BulkstockInfoService;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.common.util.CollectionUtils;
import com.yuexunit.finance.common.util.LongUtils;
import com.yuexunit.finance.member.entity.LogisticsClerkEntity;
import com.yuexunit.finance.member.service.LogisticsClerkService;
import com.yuexunit.finance.project.action.v1.model.BulkstockInventory;
import com.yuexunit.finance.project.action.v1.model.input.ContainerTallyingSubmitParams;
import com.yuexunit.finance.project.action.v1.model.input.SignSyncParams;
import com.yuexunit.finance.project.action.v1.model.input.TallySyncParams;
import com.yuexunit.finance.project.action.v1.model.input.TallySyncParams.TallyBulkstock;
import com.yuexunit.finance.project.action.v1.model.input.TallyingParams;
import com.yuexunit.finance.project.action.v1.model.input.TallyingUpdateParams;
import com.yuexunit.finance.project.action.v1.model.output.DeliveryDetail;
import com.yuexunit.finance.project.action.v1.model.output.DeliveryLineInfo;
import com.yuexunit.finance.project.action.v1.model.output.SupervisionConfirmationDetail;
import com.yuexunit.finance.project.action.v1.model.output.TallyingDetail;
import com.yuexunit.finance.project.action.v1.model.output.TallyingLineInfo;
import com.yuexunit.finance.project.entity.ContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.ContainerBulkstockHistoryEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryHistoryEntity;
import com.yuexunit.finance.project.entity.ContainerInventorySignEntity;
import com.yuexunit.finance.project.entity.DeliveryEntity;
import com.yuexunit.finance.project.entity.DeliveryNoticeEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.PickupExchangeContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.PickupExchangeContainerEntity;
import com.yuexunit.finance.project.entity.RecieveNoticeEntity;
import com.yuexunit.finance.project.entity.RecieveNoticeInventoryEntity;
import com.yuexunit.finance.project.entity.SupervisionConfirmationEntity;
import com.yuexunit.finance.project.entity.TallyingEntity;
import com.yuexunit.finance.project.entity.lexicon.AbnormalStateEnum;
import com.yuexunit.finance.project.entity.lexicon.AbnormalTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.BulkstockSourceEnum;
import com.yuexunit.finance.project.entity.lexicon.TallyingStateEnum;
import com.yuexunit.finance.project.service.ContainerBulkstockHistoryService;
import com.yuexunit.finance.project.service.ContainerBulkstockService;
import com.yuexunit.finance.project.service.ContainerInventoryHistoryService;
import com.yuexunit.finance.project.service.ContainerInventoryService;
import com.yuexunit.finance.project.service.FinanceBulkstockService;
import com.yuexunit.finance.project.service.PickupExchangeContainerBulkstockService;
import com.yuexunit.finance.project.service.RecieveNoticeInventoryService;
import com.yuexunit.finance.project.service.RecieveNoticeService;
import com.yuexunit.finance.project.service.TallyingService;
import com.yuexunit.fs.domain.FileEntry;
import com.yuexunit.fs.service.TransferService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.util.DateUtil;

/**
 * @ClassName: TallyingCastor
 * @Description: 理货配送
 * @author chenxy
 * @date 2015年11月19日 下午8:50:59
 */
public class TallyingDeliveryCastor {

	public static TallyingEntity fromRecieveNoticeEntity(TallyingParams params) {
		RecieveNoticeService recieveNoticeService = ComponentFactory.loadClass(RecieveNoticeService.class);
		RecieveNoticeEntity recieveNotice = recieveNoticeService.inquireRecieveNoticeDetail(params.getRecieveNoticeId());
		if (!(params instanceof TallyingUpdateParams) && BulkstockSourceEnum.REPEAT == recieveNotice.getBulkstockSource()) {
			throw new BusinessException("再次理货任务已经分配,不需要生成新的理货任务");
		}
		TallyingEntity tallying = new TallyingEntity();
		BeanUtils.copyProperties(recieveNotice, tallying);
		BeanUtils.copyProperties(params, tallying);

		LogisticsClerkService logisticsClerkService = ComponentFactory.loadClass(LogisticsClerkService.class);
		LogisticsClerkEntity clerkEntity = logisticsClerkService.inqueryLogisticsClerkDetail(params.getClerkId());
		tallying.setClerkId(params.getClerkId());
		tallying.setClerkMobile(clerkEntity.getClerkMobile());
		tallying.setClerkName(clerkEntity.getClerkName());

		tallying.setTallyingState(TallyingStateEnum.WAIT_TALLY);
		tallying.setWithCar(BooleanUtils.toBoolean(params.getWithCar()));
		return tallying;
	}

	public static Map<String, List<TallyingEntity>> fromTallying(TallyingEntity tallyingEntity, TallyingParams params) {
		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		RecieveNoticeService recieveNoticeService = ComponentFactory.loadClass(RecieveNoticeService.class);
		RecieveNoticeEntity recieveNotice = recieveNoticeService.inquireRecieveNoticeDetail(tallyingEntity.getRecieveNoticeId());
		Map<String, List<TallyingEntity>> queue = new HashMap<>();
		Set<String> caseNumbers = new HashSet<>();
		for (int i = 0; i < params.getCaseQueue().length; i++) {
			if (StringUtils.isNotBlank(params.getCaseNumber()[i])) {
				if (caseNumbers.contains(params.getCaseNumber()[i])) {
					throw new BusinessException("箱号:" + params.getCaseNumber()[i] + "重复");
				} else {
					caseNumbers.add(params.getCaseNumber()[i]);
				}
			}
			List<TallyingEntity> tallys = new ArrayList<>();
			ContainerInventoryHistoryEntity inventory = new ContainerInventoryHistoryEntity();
			inventory.setFinanceId(tallyingEntity.getFinanceId());
			inventory.setFinanceNumber(tallyingEntity.getFinanceNumber());
			inventory.setEnterpriseId(tallyingEntity.getEnterpriseId());
			inventory.setEnterpriseName(tallyingEntity.getEnterpriseName());
			inventory.setRecieveNoticeId(tallyingEntity.getRecieveNoticeId());
			inventory.setTallyingCompanyId(tallyingEntity.getLogisticsCompanyId());

			inventory.setWaybillNumber(CollectionUtils.getArrayIndexValue(params.getWaybillNumber(), i).trim());
			inventory.setCaseNumber(CollectionUtils.getArrayIndexValue(params.getCaseNumber(), i).trim());
			inventory.setCaseSize(CollectionUtils.getArrayIndexValue(params.getCaseSize(), i).trim());
			inventory.setModel(inventory.getCaseSize().replaceAll("[^0-9]", ""));
			inventory.setDimension(inventory.getCaseSize().replaceAll("[0-9]", ""));
			if (params instanceof TallyingUpdateParams) { // 修改不允许出现箱量
				params.getCaseQuantity()[i] = 1;
			}
			if (params.getCaseQuantity()[i] > 1) { // 存在箱量
				for (int q = 0; q < params.getCaseQuantity()[i]; q++) {
					ContainerInventoryHistoryEntity clone = inventory.clone();
					inventory.setCaseNumber(null);

					TallyingEntity tallying = tallyingEntity.clone();
					tallyingEntity.setTallyingId(null);

					tallying.setContainerInventoryHistory(clone);
					tallys.add(tallying);
				}
			} else {
				TallyingEntity tallying = tallyingEntity.clone();
				tallys.add(tallying);
				if (params instanceof TallyingUpdateParams) {
					tallyingEntity.setTallyingId(((TallyingUpdateParams) params).getTallyingId());
				} else {
					tallyingEntity.setTallyingId(null);
				}
				tallying.setContainerInventoryHistory(inventory);
				if (StringUtils.isNotBlank(inventory.getWaybillNumber()) && StringUtils.isNotBlank(inventory.getCaseNumber())) {
					List<ContainerInventoryEntity> exists = containerInventoryService.inquireContainerInventory(null, inventory.getWaybillNumber(), inventory.getCaseNumber());
					if (!exists.isEmpty()) {
						throw new BusinessException("运单号[" + inventory.getWaybillNumber() + "]下已经存在箱号[" + inventory.getCaseNumber() + "]");
					}
					if (BulkstockSourceEnum.LOGISTICS == recieveNotice.getBulkstockSource()) { // 物流自理
						ContainerInventoryHistoryService containerInventoryHistoryService = ComponentFactory.loadClass(ContainerInventoryHistoryService.class);
						List<ContainerInventoryHistoryEntity> list = containerInventoryHistoryService.inquireLogisticsContainerInventoryList(inventory.getWaybillNumber(), inventory.getCaseNumber());
						if (!list.isEmpty()) {
							throw new BusinessException("运单号[" + inventory.getWaybillNumber() + "]下已经存在箱号[" + inventory.getCaseNumber() + "]");
						}
					}
				}
			}
			queue.put(params.getCaseQueue()[i], tallys);
		}
		return queue;
	}

	public static List<ContainerBulkstockHistoryEntity> fromTallying(TallyingEntity tallying, Map<String, List<TallyingEntity>> queue, TallyingParams params) {
		FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);
		RecieveNoticeInventoryService recieveNoticeInventoryService = ComponentFactory.loadClass(RecieveNoticeInventoryService.class);
		BulkstockInfoService bulkstockInfoService = ComponentFactory.loadClass(BulkstockInfoService.class);
		List<ContainerBulkstockHistoryEntity> bulkstocks = new ArrayList<>();
		if (params.getBulkstockCaseQueue() == null) {
			return bulkstocks;
		}
		for (int i = 0; i < params.getBulkstockCaseQueue().length; i++) {
			ContainerBulkstockHistoryEntity bulkstock = new ContainerBulkstockHistoryEntity();
			bulkstock.setFinanceId(tallying.getFinanceId());
			bulkstock.setTallyingId(tallying.getTallyingId());

			RecieveNoticeInventoryEntity recieveNoticeBulkstock = recieveNoticeInventoryService.inquireRecieveNoticeDetail(params.getRecieveNoticeDetailId()[i]);
			bulkstock.setNoticeInventoryId(recieveNoticeBulkstock.getNoticeInventoryId());
			bulkstock.setBulkstockCategoryId(recieveNoticeBulkstock.getBulkstockCategoryId());
			bulkstock.setBulkstockInfoId(recieveNoticeBulkstock.getBulkstockInfoId());
			bulkstock.setBulkstockName(recieveNoticeBulkstock.getBulkstockName());
			bulkstock.setSpecification(recieveNoticeBulkstock.getSpecification());
			bulkstock.setUnit(recieveNoticeBulkstock.getUnit());
			bulkstock.setNoticeInventoryId(recieveNoticeBulkstock.getNoticeInventoryId());
			BulkstockInfoEntity bulkstockInfo = bulkstockInfoService.inquireBulkstockInfo(bulkstock.getBulkstockInfoId());
			bulkstock.setMeasurement(bulkstockInfo.getMeasurement());
			if (recieveNoticeBulkstock.getBulkstockId() != null) {
				FinanceBulkstockEntity fbe = financeBulkstockService.inquireFinanceBulkstock(recieveNoticeBulkstock.getBulkstockId());
				bulkstock.setBulkstockId(fbe.getBulkstockId());
				bulkstock.setBulkstockPrice(fbe.getBulkstockPrice());
				bulkstock.setEvaluatePrice(fbe.getEvaluatePrice());
				bulkstock.setFinancePrice(fbe.getFinancePrice());
			}
			bulkstock.setTrayNumber(CollectionUtils.getArrayIndexValue(params.getTrayNumber(), i));
			if (params instanceof TallyingUpdateParams) { // 修改不允许出现箱量
				try {
					bulkstock.setBulkstockHistoryId(CollectionUtils.getArrayIndexValue(((TallyingUpdateParams) params).getBulkstockHistoryId(), i));
				} catch (Exception e) {
				}
			}

			List<TallyingEntity> inventories = queue.get(params.getBulkstockCaseQueue()[i]);
			BigDecimal plannedQuantity = params.getPlannedQuantity()[i];
			BigDecimal plannedVolume = params.getPlannedVolume()[i];
			if (plannedVolume == null) {
				throw new BusinessException("指定货物,体积不允许为空");
			}
			BigDecimal plannedWeight = params.getPlannedWeight()[i];
			if (plannedWeight == null) {
				throw new BusinessException("指定货物,重量不允许为空");
			}
			BigDecimal size = new BigDecimal(inventories.size());
			for (int j = 0; j < inventories.size(); j++) {
				TallyingEntity tally = inventories.get(j);
				ContainerInventoryHistoryEntity container = tally.getContainerInventoryHistory();
				ContainerBulkstockHistoryEntity cbe = bulkstock.clone();
				if (j != inventories.size() - 1) {
					cbe.setPlannedQuantity(params.getPlannedQuantity()[i].subtract(size));
					plannedQuantity = plannedQuantity.subtract(cbe.getPlannedQuantity());

					cbe.setPlannedVolume(params.getPlannedVolume()[i].divide(size, 2));
					plannedVolume = plannedVolume.subtract(cbe.getPlannedVolume());

					cbe.setPlannedWeight(params.getPlannedWeight()[i].divide(size, 2));
					plannedWeight = plannedWeight.subtract(cbe.getPlannedWeight());
				} else {
					cbe.setPlannedQuantity(plannedQuantity);
					cbe.setPlannedVolume(plannedVolume);
					cbe.setPlannedWeight(plannedWeight);
				}

				if (MeasurementEnum.VOLUME == cbe.getMeasurement()) { // 体积计价
					cbe.setValuationQuantity(cbe.getVolume());
				} else { // 重量计价
					cbe.setValuationQuantity(cbe.getWeight());
				}
				cbe.setInventoryHistoryId(container.getInventoryHistoryId());
				bulkstocks.add(cbe);
			}
		}
		return bulkstocks;
	}

	public static void completeFromTallyingSubmit(ContainerInventoryHistoryEntity inventory, TallyingEntity tallyingEntity, ContainerTallyingSubmitParams params) {
		BeanUtils.copyProperties(params, inventory);
		inventory.setFinanceId(tallyingEntity.getFinanceId());
		inventory.setFinanceNumber(tallyingEntity.getFinanceNumber());
		inventory.setEnterpriseId(tallyingEntity.getEnterpriseId());
		inventory.setEnterpriseName(tallyingEntity.getEnterpriseName());
		inventory.setTallyingId(tallyingEntity.getTallyingId());
		inventory.setTallyingCompanyId(tallyingEntity.getLogisticsCompanyId());
		inventory.setTallyingState(Boolean.TRUE);
		inventory.setTallyDateTime(new Date());

		inventory.setAbnormal(BooleanUtils.toBoolean(params.getAbnormal()));
		if (inventory.validateAbnormal()) {
			inventory.setAbnormalType(AbnormalTypeEnum.TALLY);
			inventory.setAbnormalState(AbnormalStateEnum.valueOf(params.getTallyExAbnormalState()));
		}
		inventory.setTallyExAbnormalState(AbnormalStateEnum.valueOf(params.getTallyExAbnormalState()));
		return;
	}

	public static List<ContainerBulkstockHistoryEntity> fromTallyingSubmit(ContainerTallyingSubmitParams params, ContainerInventoryHistoryEntity inventory) {
		FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);
		ContainerBulkstockHistoryService containerBulkstockService = ComponentFactory.loadClass(ContainerBulkstockHistoryService.class);
		RecieveNoticeInventoryService recieveNoticeInventoryService = ComponentFactory.loadClass(RecieveNoticeInventoryService.class);
		BulkstockInfoService bulkstockInfoService = ComponentFactory.loadClass(BulkstockInfoService.class);
		List<ContainerBulkstockHistoryEntity> bulkstocks = new ArrayList<>();
		for (int i = 0; i < params.getRecieveNoticeDetailId().length; i++) {
			ContainerBulkstockHistoryEntity bulkstock = new ContainerBulkstockHistoryEntity();
			bulkstock.setBulkstockHistoryId(CollectionUtils.getArrayIndexValue(params.getBulkstockHistoryId(), i));
			bulkstock.setFinanceId(inventory.getFinanceId());
			bulkstock.setTallyingId(inventory.getTallyingId());
			bulkstock.setNoticeInventoryId(params.getRecieveNoticeDetailId()[i]);
			bulkstock.setInventoryHistoryId(inventory.getInventoryHistoryId());

			if (!LongUtils.isPrimaryKey(bulkstock.getBulkstockHistoryId())) {
				RecieveNoticeInventoryEntity recieveNoticeBulkstock = recieveNoticeInventoryService.inquireRecieveNoticeDetail(bulkstock.getNoticeInventoryId());
				bulkstock.setBulkstockId(recieveNoticeBulkstock.getBulkstockId());
				bulkstock.setBulkstockCategoryId(recieveNoticeBulkstock.getBulkstockCategoryId());
				bulkstock.setBulkstockInfoId(recieveNoticeBulkstock.getBulkstockInfoId());
				bulkstock.setBulkstockName(recieveNoticeBulkstock.getBulkstockName());
				bulkstock.setSpecification(recieveNoticeBulkstock.getSpecification());
				BulkstockInfoEntity bulkstockInfo = bulkstockInfoService.inquireBulkstockInfo(bulkstock.getBulkstockInfoId());
				bulkstock.setMeasurement(bulkstockInfo.getMeasurement());
				bulkstock.setPlannedQuantity(BigDecimal.ZERO);
				bulkstock.setPlannedVolume(BigDecimal.ZERO);
				bulkstock.setPlannedWeight(BigDecimal.ZERO);
				if (bulkstock.getBulkstockId() != null) {
					FinanceBulkstockEntity fbe = financeBulkstockService.inquireFinanceBulkstock(bulkstock.getBulkstockId());
					bulkstock.setUnit(fbe.getUnit());
					bulkstock.setBulkstockPrice(fbe.getBulkstockPrice());
					bulkstock.setEvaluatePrice(fbe.getEvaluatePrice());
					bulkstock.setFinancePrice(fbe.getFinancePrice());
				}
				containerBulkstockService.createContainerBulkstock(bulkstock);
			}
			bulkstock.setFilesUuid(CollectionUtils.getArrayIndexValue(params.getFilesUuid(), i));
			bulkstock.setTrayNumber(CollectionUtils.getArrayIndexValue(params.getTrayNumber(), i));
			bulkstock.setQuantity(CollectionUtils.getArrayIndexValue(params.getQuantity(), i));
			bulkstock.setVolume(CollectionUtils.getArrayIndexValue(params.getVolume(), i));
			bulkstock.setWeight(CollectionUtils.getArrayIndexValue(params.getWeight(), i));
			bulkstock.setAbnormal(BooleanUtils.toBoolean(CollectionUtils.getArrayIndexValue(params.getBulkstockAbnormal(), i)));
			bulkstock.setAbnormalComment(CollectionUtils.getArrayIndexValue(params.getBulkstockAbnormalComment(), i));
			if (bulkstock.getQuantity() == null) {
				throw new BusinessException(bulkstock.getBulkstockName() + "：理货数量不允许为空");
			}
			if (MeasurementEnum.VOLUME == bulkstock.getMeasurement()) { // 体积计价
				if (bulkstock.getVolume() == null || bulkstock.getVolume().compareTo(BigDecimal.ZERO) <= 0) {
					throw new BusinessException("该商品以体积计价,理货体积不允许为空或小于0");
				}
				bulkstock.setValuationQuantity(bulkstock.getVolume());
			} else { // 重量计价
				if (bulkstock.getWeight() == null || bulkstock.getWeight().compareTo(BigDecimal.ZERO) <= 0) {
					throw new BusinessException("该商品以重量计价,理货重量不允许为空或小于0");
				}
				bulkstock.setValuationQuantity(bulkstock.getWeight());
			}
			bulkstocks.add(bulkstock);
		}
		return bulkstocks;
	}

	private static void completeTallyingLineInfo(TallyingLineInfo info, TallyingEntity entity) {
		BeanUtils.copyProperties(entity, info);
		info.setTallyingState(entity.getTallyingState().ordinal());
		info.setUserDefined(BooleanUtils.toIntegerObject(entity.getUserDefined()));
		info.setWithCar(BooleanUtils.toIntegerObject(entity.getWithCar()));
		info.setAbnormal(1);
		ContainerInventoryHistoryService bulkstockInventoryHistoryService = ComponentFactory.loadClass(ContainerInventoryHistoryService.class);
		List<ContainerInventoryHistoryEntity> inventories = bulkstockInventoryHistoryService.inquireTallyingContainerInventoryList(entity.getTallyingId());
		for (ContainerInventoryHistoryEntity cihe : inventories) {
			info.getContainerInventorys().add(BulkstockCastor.toContainerInventoryHistory(cihe));
			if (cihe.validateAbnormal()) {
				info.setAbnormal(0);
			}
		}
		info.setCaseQuantity(inventories.size());
	}

	public static TallyingDetail toTallyingDetail(TallyingEntity entity) {
		TallyingDetail detail = new TallyingDetail();
		completeTallyingLineInfo(detail, entity);
		return detail;
	}

	public static TallyingLineInfo toTallyingLineInfo(TallyingEntity entity) {
		TallyingLineInfo info = new TallyingLineInfo();
		completeTallyingLineInfo(info, entity);

		ContainerBulkstockService containerBulkstockService = ComponentFactory.loadClass(ContainerBulkstockService.class);
		List<ContainerBulkstockEntity> containerBulkstockList = containerBulkstockService.inquireTallyingContainerBulkstockList(entity.getTallyingId());
		Map<Long, BulkstockInventory> bulkstockInventories = new HashMap<>();
		for (ContainerBulkstockEntity cbe : containerBulkstockList) {
			BulkstockInventory bulkstockInventory = bulkstockInventories.get(cbe.getBulkstockId());
			if (bulkstockInventory == null) {
				bulkstockInventory = new BulkstockInventory();
				bulkstockInventory.setBulkstockInfoId(cbe.getBulkstockInfoId());
				bulkstockInventory.setBulkstockName(cbe.getBulkstockName());
				bulkstockInventory.setSpecification(cbe.getSpecification());
				bulkstockInventory.setQuantity(BigDecimal.ZERO);
				bulkstockInventory.setUnit(cbe.getUnit());
				bulkstockInventories.put(cbe.getBulkstockInfoId(), bulkstockInventory);
			}
			bulkstockInventory.setQuantity(bulkstockInventory.getQuantity().add(cbe.getQuantity() == null ? BigDecimal.ZERO : cbe.getQuantity()));
		}
		info.setBulkstockInventories(new ArrayList<>(bulkstockInventories.values()));
		return info;
	}

	public static TallyingLineInfo toClerkTallyingLineInfo(TallyingEntity entity) {
		TallyingLineInfo info = new TallyingLineInfo();
		completeTallyingLineInfo(info, entity);
		ContainerBulkstockService containerBulkstockService = ComponentFactory.loadClass(ContainerBulkstockService.class);
		List<ContainerBulkstockEntity> containerBulkstockList = containerBulkstockService.inquireTallyingContainerBulkstockList(entity.getTallyingId());
		if (!containerBulkstockList.isEmpty()) {
			Map<Long, BulkstockInventory> bulkstockInventories = new HashMap<>();
			for (ContainerBulkstockEntity cbe : containerBulkstockList) {
				BulkstockInventory bulkstockInventory = bulkstockInventories.get(cbe.getBulkstockId());
				if (bulkstockInventory == null) {
					bulkstockInventory = new BulkstockInventory();
					bulkstockInventory.setBulkstockInfoId(cbe.getBulkstockInfoId());
					bulkstockInventory.setBulkstockName(cbe.getBulkstockName());
					bulkstockInventory.setSpecification(cbe.getSpecification());
					bulkstockInventory.setQuantity(BigDecimal.ZERO);
					bulkstockInventory.setUnit(cbe.getUnit());
					bulkstockInventories.put(cbe.getBulkstockInfoId(), bulkstockInventory);
				}
				bulkstockInventory.setQuantity(bulkstockInventory.getQuantity().add(cbe.getPlannedQuantity() == null ? BigDecimal.ZERO : cbe.getPlannedQuantity()));
			}
			info.setBulkstockInventories(new ArrayList<>(bulkstockInventories.values()));
		} else {
			RecieveNoticeInventoryService recieveNoticeInventoryService = ComponentFactory.loadClass(RecieveNoticeInventoryService.class);
			List<RecieveNoticeInventoryEntity> inquireRecieveNoticeInventoryList = recieveNoticeInventoryService.inquireRecieveNoticeInventoryList(entity.getRecieveNoticeId());
			Map<Long, BulkstockInventory> bulkstockInventories = new HashMap<>();
			for (RecieveNoticeInventoryEntity cbe : inquireRecieveNoticeInventoryList) {
				BulkstockInventory bulkstockInventory = bulkstockInventories.get(cbe.getBulkstockId());
				if (bulkstockInventory == null) {
					bulkstockInventory = new BulkstockInventory();
					bulkstockInventory.setBulkstockInfoId(cbe.getBulkstockInfoId());
					bulkstockInventory.setBulkstockName(cbe.getBulkstockName());
					bulkstockInventory.setSpecification(cbe.getSpecification());
					bulkstockInventory.setQuantity(cbe.getQuantity());
					bulkstockInventory.setUnit(cbe.getUnit());
					bulkstockInventory.setRecieveNoticeDetailId(cbe.getNoticeInventoryId());
					bulkstockInventories.put(cbe.getBulkstockInfoId(), bulkstockInventory);
				}
				bulkstockInventory.setQuantity(bulkstockInventory.getQuantity().add(cbe.getQuantity()));
			}
			info.setBulkstockInventories(new ArrayList<>(bulkstockInventories.values()));
		}

		return info;
	}

	// ================================================================================================================================================================================//
	public static DeliveryEntity fromDelivery(DeliveryNoticeEntity noticeEntity, Long clerkId, String clerkName, String clerkMobile) {
		DeliveryEntity entity = new DeliveryEntity();
		entity.setClerkId(clerkId);
		entity.setClerkMobile(clerkMobile);
		entity.setClerkName(clerkName);
		entity.setDeliveryNoticeId(noticeEntity.getDeliveryNoticeId());
		entity.setPickupId(noticeEntity.getPickupId());
		entity.setLogisticsCompanyId(noticeEntity.getLogisticsCompanyId());
		entity.setLogisticsCompanyName(noticeEntity.getLogisticsCompanyName());
		entity.setFinanceId(noticeEntity.getFinanceId());
		entity.setFinanceNumber(noticeEntity.getFinanceNumber());
		return entity;
	}

	public static DeliveryDetail toDeliveryDetail(DeliveryEntity entity) {
		DeliveryDetail detail = new DeliveryDetail();
		BeanUtils.copyProperties(entity, detail);
		detail.setDeliveryState(entity.getDeliveryState() == null ? 0 : entity.getDeliveryState().ordinal());
		ContainerInventoryService bulkstockInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		List<ContainerInventoryEntity> inventoryEntityList = bulkstockInventoryService.inquireDeliveryContainerInventoryList(entity.getDeliveryId());
		for (ContainerInventoryEntity cie : inventoryEntityList) {
			detail.getContainerInventorys().add(BulkstockCastor.toContainerInventory(cie, Boolean.FALSE));
		}
		return detail;
	}

	public static DeliveryDetail toDeliveryDetailByCondition(DeliveryEntity entity, String caseNumber, String waybillNumber) {
		DeliveryDetail detail = new DeliveryDetail();
		BeanUtils.copyProperties(entity, detail);
		detail.setDeliveryState(entity.getDeliveryState().ordinal());
		ContainerInventoryService bulkstockInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		List<ContainerInventoryEntity> inventoryEntityList = bulkstockInventoryService.inquireDeliveryContainerInventoryListByCondition(entity.getDeliveryId(), caseNumber, waybillNumber);
		for (ContainerInventoryEntity cie : inventoryEntityList) {
			detail.getContainerInventorys().add(BulkstockCastor.toContainerInventory(cie, Boolean.FALSE));
		}
		return detail;
	}

	public static DeliveryLineInfo toDeliveryLineInfo(DeliveryEntity entity) {
		DeliveryLineInfo info = new DeliveryLineInfo();
		BeanUtils.copyProperties(entity, info);
		info.setDeliveryState(entity.getDeliveryState().ordinal());
		return info;
	}

	public static SupervisionConfirmationDetail toSupervisionConfirmationDetail(SupervisionConfirmationEntity entity) {
		SupervisionConfirmationDetail info = new SupervisionConfirmationDetail();
		BeanUtils.copyProperties(entity, info);
		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		List<ContainerInventoryEntity> inventories = containerInventoryService.inquireSupervisionConfirmationContainerInventoryList(entity.getConfirmationId());
		for (ContainerInventoryEntity cie : inventories) {
			info.getContainerInventories().add(BulkstockCastor.toContainerInventory(cie, Boolean.FALSE));
		}
		return info;
	}

	private static String downloadImage(String imageUrl) {
		if (StringUtils.isBlank(imageUrl)) {
			return null;
		}
		try {
			TransferService fileService = ComponentFactory.loadClass(TransferService.class);
			String imageName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
			CloseableHttpClient httpclient = HttpClients.custom().build();
			HttpGet httpget = new HttpGet(imageUrl);
			CloseableHttpResponse response = null;
			try {
				response = httpclient.execute(httpget);
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					InputStream instream = entity.getContent();
					FileEntry fileEntry = fileService.uploadFile(imageName, instream);
					return fileEntry.getFileUuid();
				}
			} catch (Exception e) {
			} finally {
				httpget.abort();
				if (response != null) {
					try {
						response.close();
					} catch (Exception e) {
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String downloadImage(String[] imageUrls) {
		if (imageUrls == null || imageUrls.length <= 0) {
			return null;
		}

		StringBuffer sb = new StringBuffer();
		for (String imageUrl : imageUrls) {
			String fileUuid = downloadImage(imageUrl);
			if (fileUuid != null) {
				sb.append(fileUuid).append(",");
			}
		}
		return sb.substring(1).toString();
	}

	public static TallyingEntity fromSyncTally(TallySyncParams param) {
		if (StringUtils.isBlank(param.getWaybillNumber()) || StringUtils.isBlank(param.getCaseNumber())) {
			throw new BusinessException("箱号和运单号不允许为空");
		}
		RecieveNoticeService recieveNoticeService = ComponentFactory.loadClass(RecieveNoticeService.class);
		LogisticsClerkService logisticsClerkService = ComponentFactory.loadClass(LogisticsClerkService.class);
		FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);
		ContainerInventoryHistoryService containerInventoryHistoryService = ComponentFactory.loadClass(ContainerInventoryHistoryService.class);
		TallyingService tallyingService = ComponentFactory.loadClass(TallyingService.class);

		// 查找收货通知
		RecieveNoticeEntity recieveNotice = recieveNoticeService.inquireNumberRecieveNotice(param.getRecieveNoticeNumber());
		if (recieveNotice == null) {
			throw new BusinessException("收货通知编号:" + param.getRecieveNoticeNumber() + "不存在");
		}
		// 验证该收货通知下箱号是否已理(重复的则过滤)
		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		List<ContainerInventoryEntity> temps = containerInventoryService.inquireContainerInventory(null, param.getWaybillNumber(), param.getCaseNumber());
		if (!temps.isEmpty()) {
			throw new BusinessException("运单号[" + param.getWaybillNumber() + "]下已经存在箱号[" + param.getCaseNumber() + "]");
		}
		List<ContainerInventoryHistoryEntity> exists = containerInventoryHistoryService.inquireRecieveNoticeContainerInventory(param.getWaybillNumber(), param.getCaseNumber());
		ContainerInventoryHistoryEntity container = null;
		for (ContainerInventoryHistoryEntity p : exists) {
			if (recieveNotice.getRecieveNoticeId().equals(p.getRecieveNoticeId())) {
				if (p.getTallyingState()) {
					throw new BusinessException("箱已理");
				}
				container = p;
			}
		}
		TallyingEntity tally = null;
		if (container == null) { // 无改箱信息
			// 构造理货任务
			tally = new TallyingEntity();
			tally.setDriver(null);
			tally.setDriverAddress(param.getDriverAddress());
			tally.setDriverTel(null);
			tally.setEnterpriseId(recieveNotice.getEnterpriseId());
			tally.setEnterpriseName(recieveNotice.getEnterpriseName());
			tally.setFinanceId(recieveNotice.getFinanceId());
			tally.setFinanceNumber(recieveNotice.getFinanceNumber());
			tally.setFinishedDateTime(DateUtil.now());
			tally.setFinishedFileUuid(null);
			tally.setLimitDate(null);
			tally.setLogisticsCompanyId(recieveNotice.getLogisticsCompanyId());
			tally.setLogisticsCompanyName(recieveNotice.getLogisticsCompanyName());
			tally.setPlateNumber(null);
			tally.setRecieveNoticeId(recieveNotice.getRecieveNoticeId());
			tally.setStartDate(param.getStartDate());
			tally.setTallyingFile(null);
			tally.setTallyingState(TallyingStateEnum.ALREADY_TALLY);
			tally.setUserDefined(Boolean.TRUE);
			tally.setWithCar(Boolean.TRUE);

			tally.setClerkMobile(param.getClerkMobile());
			LogisticsClerkEntity clerk = logisticsClerkService.inqueryLogisticsClerk(tally.getLogisticsCompanyId(), param.getClerkMobile());
			if (clerk != null) {
				tally.setClerkId(clerk.getClerkId());
				tally.setClerkName(clerk.getClerkName());
			}

			// 构造箱信息
			container = new ContainerInventoryHistoryEntity();
			container.setRecieveNoticeId(tally.getRecieveNoticeId());
			container.setEnterpriseId(tally.getEnterpriseId());
			container.setEnterpriseName(tally.getEnterpriseName());
			container.setFinanceId(tally.getFinanceId());
			container.setFinanceNumber(tally.getFinanceNumber());
			container.setTallyingCompanyId(tally.getLogisticsCompanyId());
			container.setWaybillNumber(param.getWaybillNumber());
			container.setCaseNumber(param.getCaseNumber());
			container.setCaseSize(param.getDimension() + param.getModel());
			container.setModel(param.getModel());
			container.setDimension(param.getDimension());
			container.setFacingSlip(param.getFacingSlip());
			container.setFacingSlipNext(param.getFacingSlipNext());
			container.setAbnormalState(AbnormalStateEnum.valueOf(param.getTallyExAbnormalState()));
			if (AbnormalStateEnum.UNKNOWN == container.getAbnormalState()) {
				container.setAbnormal(Boolean.TRUE);
			} else {
				container.setAbnormal(Boolean.FALSE);
				container.setAbnormalType(AbnormalTypeEnum.TALLY);
			}
			container.setTallyingState(Boolean.TRUE);
			container.setTallyDateTime(param.getTallyDateTime());
		} else { // 存在计划的箱信息
			tally = tallyingService.inquireTallying(container.getTallyingId());
			tally.setTallyingState(TallyingStateEnum.IN_TALLY);

			container.setWaybillNumber(param.getWaybillNumber());
			container.setCaseNumber(param.getCaseNumber());
			container.setCaseSize(param.getDimension() + param.getModel());
			container.setModel(param.getModel());
			container.setDimension(param.getDimension());
			container.setFacingSlip(param.getFacingSlip());
			container.setFacingSlipNext(param.getFacingSlipNext());
			container.setAbnormalState(AbnormalStateEnum.valueOf(param.getTallyExAbnormalState()));
			if (AbnormalStateEnum.UNKNOWN == container.getAbnormalState()) {
				container.setAbnormal(Boolean.TRUE);
			} else {
				container.setAbnormal(Boolean.FALSE);
				container.setAbnormalType(AbnormalTypeEnum.TALLY);
			}
			container.setTallyingState(Boolean.TRUE);
			container.setTallyDateTime(param.getTallyDateTime());
		}
		tally.setContainerInventoryHistory(container);

		// 构造箱理货信息
		container.setTallyAddress(param.getTallyAddress());
		container.setTallyPreFile(downloadImage(param.getTallyPreFile()));
		container.setTallySuffixFile(downloadImage(param.getTallySuffixFile()));
		container.setTallyRemark(param.getTallyRemark());
		container.setTallyExAddress(null);
		container.setTallyExRemark(param.getTallyRemark());
		container.setTallyExAbnormalFile(downloadImage(param.getTallyExAbnormalFile()));
		container.setTallyExAbnormalState(AbnormalStateEnum.valueOf(param.getTallyExAbnormalState()));

		ContainerBulkstockHistoryService containerBulkstockHistoryService = ComponentFactory.loadClass(ContainerBulkstockHistoryService.class);
		// 箱货物信息（一箱一货）
		List<ContainerBulkstockHistoryEntity> bulkstocks = containerBulkstockHistoryService.inquireContainerHistoryBulkstockList(container.getInventoryHistoryId());
		for (TallyBulkstock bulkstock : param.getTallyBulkstocks()) {
			ContainerBulkstockHistoryEntity cbe = null;
			if (bulkstocks.isEmpty()) {
				cbe = new ContainerBulkstockHistoryEntity();
			} else {
				cbe = bulkstocks.get(0);
			}
			cbe.setFinanceId(container.getFinanceId());
			cbe.setTrayNumber(bulkstock.getTrayNumber());
			cbe.setBulkstockName(bulkstock.getBulkstockName());
			cbe.setSpecification(bulkstock.getSpecification());
			cbe.setQuantity(bulkstock.getQuantity());
			if (bulkstock.getVolume() == null) {
				bulkstock.setVolume(BigDecimal.ZERO);
			}
			if (bulkstock.getWeight() == null) {
				bulkstock.setWeight(BigDecimal.ZERO);
			}
			cbe.setVolume(bulkstock.getVolume());
			cbe.setWeight(bulkstock.getWeight());
			cbe.setAbnormalComment(null);
			cbe.setFilesUuid(downloadImage(bulkstock.getFilesUuid()));
			cbe.setAbnormal(container.getAbnormal());

			List<FinanceBulkstockEntity> financeBulkstockList = financeBulkstockService.inquireFinanceBulkstockList(cbe.getFinanceId());
			if (financeBulkstockList.size() == 1) {
				FinanceBulkstockEntity financeBulkstock = financeBulkstockList.get(0);
				cbe.setBulkstockId(financeBulkstock.getBulkstockId());
				cbe.setBulkstockCategoryId(financeBulkstock.getBulkstockCategoryId());
				cbe.setBulkstockInfoId(financeBulkstock.getBulkstockInfoId());
				cbe.setUnit(financeBulkstock.getUnit());
				cbe.setMeasurement(financeBulkstock.getMeasurement());
				cbe.setBulkstockName(financeBulkstock.getBulkstockName());
				cbe.setSpecification(financeBulkstock.getSpecification());
				if (MeasurementEnum.VOLUME == cbe.getMeasurement()) { // 体积计价单位
					cbe.setValuationQuantity(cbe.getVolume());
				} else { // 重量计价单位
					cbe.setValuationQuantity(cbe.getWeight());
				}
				cbe.setBulkstockPrice(financeBulkstock.getBulkstockPrice());
				cbe.setEvaluatePrice(financeBulkstock.getEvaluatePrice());
				cbe.setFinancePrice(financeBulkstock.getFinancePrice());
			}
			bulkstocks.add(cbe);
			break;
		}
		container.setContainerBulkstockHistories(bulkstocks);
		return tally;
	}

	/** 签收同步 */
	public static ContainerInventoryEntity fromSyncContainerSign(SignSyncParams param) {
		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		RecieveNoticeService recieveNoticeService = ComponentFactory.loadClass(RecieveNoticeService.class);

		// 查找收货通知
		RecieveNoticeEntity recieveNotice = recieveNoticeService.inquireNumberRecieveNotice(param.getRecieveNoticeNumber());
		if (recieveNotice == null) {
			throw new BusinessException("收货通知编号:" + param.getRecieveNoticeNumber() + "不存在");
		}
		// 验证该收货通知下箱号是否已理(重复的则过滤)
		ContainerInventoryEntity container = containerInventoryService.inquireRecieveNoticeContainerInventory(recieveNotice.getRecieveNoticeId(), param.getCaseNumber());
		if (container == null) {
			throw new BusinessException("收货通知编号:" + param.getRecieveNoticeNumber() + "下不存在该箱信息");
		}
		if (container.getPickupId() == null) {
			throw new BusinessException("还未经用户提货,不允许签收");
		}
		if (container.getSignState()) {
			throw new BusinessException("已经签收");
		}
		container.setSignDateTime(param.getSignDateTime());
		container.setSignState(Boolean.TRUE);

		// 构造箱签收信息
		ContainerInventorySignEntity containerSign = new ContainerInventorySignEntity();
		containerSign.setInventoryId(container.getInventoryId());
		containerSign.setSignAccountor(param.getSignAccountor());
		containerSign.setSignRemark(param.getSignRemark());
		containerSign.setSignAddress(param.getSignAddress());
		containerSign.setSignPreFile(downloadImage(param.getSignPreFile()));
		containerSign.setSignSuffixFile(downloadImage(param.getSignSuffixFile()));
		containerSign.setSignSoundRecorde(downloadImage(param.getSignSoundRecorde()));
		containerSign.setSignAbnormalFile(downloadImage(param.getSignAbnormalFile()));
		containerSign.setSignAbnormalState(AbnormalStateEnum.valueOf(param.getSignAbnormalState()));
		container.setContainerInventorySign(containerSign);
		return container;
	}

	/** 换箱理货数据同步 
	 * @return */
	public static Boolean syncExchangeContainer(PickupExchangeContainerEntity pece) {
		Logger logger = LoggerFactory.getLogger(TallyingDeliveryCastor.class);
		try {
			ContainerInventoryHistoryService containerInventoryHistoryService = ComponentFactory.loadClass(ContainerInventoryHistoryService.class);
			TallyingService tallyingService = ComponentFactory.loadClass(TallyingService.class);
			List<ContainerInventoryHistoryEntity> exists = containerInventoryHistoryService.inquireLogisticsContainerInventoryList(pece.getWaybillNumber(), pece.getCaseNumber());
			if (exists.isEmpty()) {
				logger.info("运单号[" + pece.getWaybillNumber() + "]下不存在箱号[" + pece.getCaseNumber() + "]");
				//				throw new BusinessException("运单号[" + pece.getWaybillNumber() + "]下不存在箱号[" + pece.getCaseNumber() + "]");
				return Boolean.FALSE;
			}
			ContainerInventoryHistoryEntity source = exists.get(0);
			if (!source.getTallyingState()) {
				//				throw new BusinessException("同步的箱还未完成理货");
				logger.info("同步的箱还未完成理货");
				return Boolean.FALSE;
			}
			TallyingEntity tallying = tallyingService.inquireTallying(source.getTallyingId());
			pece.setClerkMobile(tallying.getClerkMobile());
			pece.setTallyAddress(source.getTallyAddress());
			pece.setTallyStartDateTime(tallying.getStartDate());
			pece.setTallyDateTime(source.getTallyDateTime());
			pece.setFacingSlip(source.getFacingSlip());
			pece.setFacingSlipNext(source.getFacingSlipNext());
			pece.setTallyRemark(source.getTallyRemark());
			pece.setTallyExAbnormalState(source.getTallyExAbnormalState());
			pece.setTallyPreFile(source.getTallyPreFile());
			pece.setTallySuffixFile(source.getTallySuffixFile());
			pece.setTallyExAbnormalFile(source.getTallyExAbnormalFile());
			pece.setCaseSize(source.getCaseSize());
			// 一箱一货
			ContainerBulkstockHistoryService containerBulkstockHistoryService = ComponentFactory.loadClass(ContainerBulkstockHistoryService.class);
			PickupExchangeContainerBulkstockService pickupExchangeContainerBulkstockService = ComponentFactory.loadClass(PickupExchangeContainerBulkstockService.class);
			List<ContainerBulkstockHistoryEntity> sourceBulkstocks = containerBulkstockHistoryService.inquireContainerHistoryBulkstockList(source.getInventoryHistoryId());
			List<PickupExchangeContainerBulkstockEntity> pecbs = pickupExchangeContainerBulkstockService.inquirePickupExchangeContainerBulkstockList(pece.getContainerId());
			PickupExchangeContainerBulkstockEntity pecb = pecbs.get(0);
			ContainerBulkstockHistoryEntity cbhe = sourceBulkstocks.get(0);
			pecb.setTrayNumber(cbhe.getTrayNumber());
			pecb.setTallyQuantity(cbhe.getQuantity());
			pecb.setTallyWeight(cbhe.getWeight());
			pecb.setTallyVolume(cbhe.getVolume());

			pecb.setQuantity(cbhe.getQuantity());
			pecb.setWeight(cbhe.getWeight());
			pecb.setVolume(cbhe.getVolume());
			pecb.setFilesUuid(cbhe.getFilesUuid());
			pece.setPickupExchangeContainerBulkstockEntity(pecb);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("换箱理货数据同步失败");
			//				throw new BusinessException("换箱理货数据同步失败");
			return Boolean.FALSE;
		}
		//		try {
		//			String url = ConfigPropertites.getProperties("exchange.container.tally.service");
		//			Map<String, String> params = new HashMap<>();
		//			params.put("boxNO", pece.getCaseNumber());
		//			params.put("billNO", pece.getWaybillNumber());
		//			String responseText = HttpClientHelper.post(url, params);
		//			logger.info("理货同步地址:" + url);
		//			logger.info("理货同步箱号:" + pece.getCaseNumber());
		//			logger.info("理货同步提单号:" + pece.getWaybillNumber());
		//			logger.info("理货数据同步结果:" + responseText);
		//			// 理货同步
		//			ExchangeContainerTallyResponse response = JSON.toBean(responseText, ExchangeContainerTallyResponse.class);
		//			Class<TallySyncParams> genicType = TallySyncParams.class;
		//			Class<ArrayList<TallySyncParams>> type = (Class<ArrayList<TallySyncParams>>) new ArrayList<TallySyncParams>().getClass();
		//			Collection<TallySyncParams> tallySyncResponse = JSON.toBeanSet(URLDecoder.decode(response.getJson(), "UTF-8"), type, genicType);
		//			TallySyncParams tallySync = tallySyncResponse.iterator().next();
		//
		//			pece.setClerkMobile(tallySync.getClerkMobile());
		//			pece.setTallyAddress(tallySync.getTallyAddress());
		//			pece.setTallyStartDateTime(tallySync.getStartDate());
		//			pece.setTallyDateTime(tallySync.getTallyDateTime());
		//			pece.setFacingSlip(tallySync.getFacingSlip());
		//			pece.setFacingSlipNext(tallySync.getFacingSlipNext());
		//			pece.setTallyRemark(tallySync.getTallyRemark());
		//			pece.setTallyExAbnormalState(AbnormalStateEnum.valueOf(tallySync.getTallyExAbnormalState()));
		//			pece.setTallyPreFile(downloadImage(tallySync.getTallyPreFile()));
		//			pece.setTallySuffixFile(downloadImage(tallySync.getTallySuffixFile()));
		//			pece.setTallyExAbnormalFile(downloadImage(tallySync.getTallyExAbnormalFile()));
		//
		//			// 一箱一货
		//			TallyBulkstock tb = tallySync.getTallyBulkstocks().get(0);
		//			PickupExchangeContainerBulkstockService pickupExchangeContainerBulkstockService = ComponentFactory.loadClass(PickupExchangeContainerBulkstockService.class);
		//			List<PickupExchangeContainerBulkstockEntity> pecbs = pickupExchangeContainerBulkstockService.inquirePickupExchangeContainerBulkstockList(pece.getContainerId());
		//			PickupExchangeContainerBulkstockEntity pecb = pecbs.get(0);
		//			pecb.setTrayNumber(tb.getTrayNumber());
		//			pecb.setTallyQuantity(tb.getQuantity());
		//			pecb.setTallyWeight(tb.getWeight());
		//			pece.setPickupExchangeContainerBulkstockEntity(pecb);
		//		} catch (Exception e1) {
		//			e1.printStackTrace();
		//			System.out.println("远程同步失败,同步本地理货数据");
		//			try {
		//				ContainerInventoryHistoryService containerInventoryHistoryService = ComponentFactory.loadClass(ContainerInventoryHistoryService.class);
		//				TallyingService tallyingService = ComponentFactory.loadClass(TallyingService.class);
		//				List<ContainerInventoryHistoryEntity> exists = containerInventoryHistoryService.inquireLogisticsContainerInventoryList(pece.getWaybillNumber(), pece.getCaseNumber());
		//				if (exists.isEmpty()) {
		//					logger.info("运单号[" + pece.getWaybillNumber() + "]下不存在箱号[" + pece.getCaseNumber() + "]");
		////					throw new BusinessException("运单号[" + pece.getWaybillNumber() + "]下不存在箱号[" + pece.getCaseNumber() + "]");
		//					return Boolean.FALSE;
		//				}
		//				ContainerInventoryHistoryEntity source = exists.get(0);
		//				if (!source.getTallyingState()) {
		////					throw new BusinessException("同步的箱还未完成理货");
		//					logger.info("同步的箱还未完成理货");
		//					return Boolean.FALSE;
		//				}
		//				TallyingEntity tallying = tallyingService.inquireTallying(source.getTallyingId());
		//				pece.setClerkMobile(tallying.getClerkMobile());
		//				pece.setTallyAddress(source.getTallyAddress());
		//				pece.setTallyStartDateTime(tallying.getStartDate());
		//				pece.setTallyDateTime(source.getTallyDateTime());
		//				pece.setFacingSlip(source.getFacingSlip());
		//				pece.setFacingSlipNext(source.getFacingSlipNext());
		//				pece.setTallyRemark(source.getTallyRemark());
		//				pece.setTallyExAbnormalState(source.getTallyExAbnormalState());
		//				pece.setTallyPreFile(source.getTallyPreFile());
		//				pece.setTallySuffixFile(source.getTallySuffixFile());
		//				pece.setTallyExAbnormalFile(source.getTallyExAbnormalFile());
		//				pece.setCaseSize(source.getCaseSize());
		//				// 一箱一货
		//				ContainerBulkstockHistoryService containerBulkstockHistoryService = ComponentFactory.loadClass(ContainerBulkstockHistoryService.class);
		//				PickupExchangeContainerBulkstockService pickupExchangeContainerBulkstockService = ComponentFactory.loadClass(PickupExchangeContainerBulkstockService.class);
		//				List<ContainerBulkstockHistoryEntity> sourceBulkstocks = containerBulkstockHistoryService.inquireContainerHistoryBulkstockList(source.getInventoryHistoryId());
		//				List<PickupExchangeContainerBulkstockEntity> pecbs = pickupExchangeContainerBulkstockService.inquirePickupExchangeContainerBulkstockList(pece.getContainerId());
		//				PickupExchangeContainerBulkstockEntity pecb = pecbs.get(0);
		//				ContainerBulkstockHistoryEntity cbhe = sourceBulkstocks.get(0);
		//				pecb.setTrayNumber(cbhe.getTrayNumber());
		//				pecb.setTallyQuantity(cbhe.getQuantity());
		//				pecb.setTallyWeight(cbhe.getWeight());
		//				pecb.setTallyVolume(cbhe.getVolume());
		//				
		//				pecb.setQuantity(cbhe.getQuantity());
		//				pecb.setWeight(cbhe.getWeight());
		//				pecb.setVolume(cbhe.getVolume());
		//				pecb.setFilesUuid(cbhe.getFilesUuid());
		//				pece.setPickupExchangeContainerBulkstockEntity(pecb);
		//			} catch (Exception e2) {
		//				e2.printStackTrace();
		//				logger.info("换箱理货数据同步失败");
		////				throw new BusinessException("换箱理货数据同步失败");
		//				return Boolean.FALSE;
		//			}

		return Boolean.TRUE;
	}

}
